package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Notice;
import com.example.springboot.entity.User;
import com.example.springboot.service.NoticeService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 功能：用户信息增删查改
 * 作者：刘涵茹
 * 日期：2024/2/14 13:51
 */

@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired//通过注解去拿@Service注解中注入容器的函数数据
            NoticeService noticeService;
    @Autowired
            UserService userService;


    /**
     * 新增信息 post
     */
    @HoneyLogs(operation = "公告", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Notice notice) {
        User currentUser = TokenUtils.getCurrentUser(); //获取当前登录的用户信息
        notice.setUserid(currentUser.getId());
        notice.setTime(DateUtil.now()); //获取当前的时间(格式: yyyy-mm-dd HH:MM:SS) 如果是today则是yyyy-mm-dd
        noticeService.save(notice);//service中的函数
        return Result.success();
    }

    /**
     * 修改信息 put
     */
    @HoneyLogs(operation = "公告", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Notice notice) {
        try {
            notice.setTime(DateUtil.now());
            noticeService.updateById(notice);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("插入数据库错误");
            } else {
                return Result.error("字数超出500字");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 单个删除信息 delete
     */
    @HoneyLogs(operation = "公告", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")//delete需要通过path相关注解使用
    public Result delete(@PathVariable Integer id) {
        noticeService.removeById(id);//service中的函数
        return Result.success();
    }

    /**
     * 批量删除信息 delete
     */
    @HoneyLogs(operation = "公告", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")//delete需要通过path相关注解使用
    public Result batchDelete(@RequestBody List<Integer> ids) {//得到数组，并传到service中
        noticeService.removeBatchByIds(ids);//service中的函数
        return Result.success();
    }

    /**
     * 查询全部的信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {//得到数组，并传到service中
        List<Notice> noticeList = noticeService.list(new QueryWrapper<Notice>().orderByDesc("id"));
        //service中的函数
        //select * from notice order by id desc
        return Result.success(noticeList);
    }

    /**
     * 查询用户公告
     */
    @GetMapping("/selectUserData")
    public Result selectUserData() {//得到数组，并传到service中
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>().orderByDesc("time");
        queryWrapper.eq("open", 1); //用户只能看到公开的公告数据
        List<Notice> userList = noticeService.list(queryWrapper);
        //service中的函数
        //select * from notice order by id desc
        return Result.success(userList);
    }

    /**
     * 单个条件查询
     * 根据id查询单个的信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {//得到数组，并传到service中
        Notice notice = noticeService.getById(id);//service中的函数
        User user = userService.getById(notice.getUserid());
        if (user != null){
            notice.setUser(user.getUsername());//已改
        }
        return Result.success(notice);
    }

    /**
     * 分页多个条件模糊查询
     * 根据title查询单个的信息
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String title) {//得到数组，并传到service中
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>().orderByDesc("id");//默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        // select * from notice where username like '%#{username}%' and name like '%#{name}%' and role like '%#{role}%'
        Page<Notice> page = noticeService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Notice> records = page.getRecords();
        for (Notice recode : records){
            Integer authorid = recode.getUserid();
            User user = userService.getById(authorid);
            if (user != null){
                recode.setUser(user.getUsername());//已改
            }
        }
        return Result.success(page);
    }
}
